import {
	getToken
} from './token.js'
import {
	addFriends,
	getPeoPhone,
	useUsrVipAccredit,
	queryApplyFriend,
	updAddFriends
} from '@/common/api/msg.js'
import store from '@/store/index.js'
import test from './loginjs/test.js'
// 这都n年了iOS依然不认识2020-12-12，需要转换为2020/12/12
export function getDate(time) {
	if (time instanceof Date) {
		return time
	}
	switch (typeof time) {
		case 'string': {
			// 2020-12-12T12:12:12.000Z、2020-12-12T12:12:12.000
			if (time.indexOf('T') > -1) {
				return new Date(time)
			}
			return new Date(time.replace(/-/g, '/'))
		}
		default:
			return new Date(time)
	}
}
//获取当前时间日期
export function getnowtime(type, date) {
	var nowtime = ''
	if (date) {
		nowtime = date
	} else {
		nowtime = new Date(Date.now());
	}
	var year = nowtime.getFullYear();
	var month = (nowtime.getMonth() + 1).toString();
	if (month.length == 1) {
		month = "0" + month;
	}
	var day = nowtime.getDate().toString();
	if (day.length == 1) {
		day = "0" + day;
	}
	var hour = nowtime.getHours().toString();
	if (hour.length == 1) {
		hour = "0" + hour;
	}
	var minute = nowtime.getMinutes().toString();
	if (minute.length == 1) {
		minute = "0" + minute;
	}
	var second = nowtime.getSeconds().toString();
	if (second.length == 1) {
		second = "0" + second;
	}
	if (type == 'YYYY-MM-DD') {
		return year + '-' + month + '-' + day;
	} else if (type == 'YYYY-MM') {
		return year + '-' + month;
	} else if (type == 'YYYY-MM-DD') {
		return year + '-' + month + '-' + day;
	} else if (type == 'YYYY-MM-DD hh:mm:ss') {
		return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	} else if (type == 'MM-DD hh:mm') {
		return month + '月' + day + '日 ' + hour + ':' + minute;
	} else if (type == 'MM-DD') {
		return month + '月' + day + '日';
	} else if (type == 'hh:mm:ss') {
		return hour + ':' + minute + ':' + second;
	} else if (type == 'hh:mm') {
		return hour + ':' + minute;
	} else if (type == 'YYYYMMDDhhmmss') {
		return year + '' + month + '' + day + '' + hour + '' + minute + '' + second;
	} else {
		return nowtime.getTime();
	}
}
//对象数组去重
export const duplicateRemoval = (oldArr, newArr, key, isSort = false) => {
	let arrs = [...oldArr, ...newArr];
	let map = new Map();
	for (let item of arrs) {
		if (!map.has(item[key])) {
			map.set(item[key], item)
		}
	}
	let data = [...map.values()];
	if (isSort) {
		let sortData = data.sort(function(a, b) {
			var value1 = a[key];
			var value2 = b[key];
			return value1.length - value2.length
		})
		return sortData
	} else {
		return data
	}
}
//添加好友申请
export async function addFriend(userId) {
	return new Promise((resolve, reject) => {
		let params = {
			status: 0,
			firendId: userId,
			friendsType: 0,
			friendTypeId: getToken('version') == 1 ? 0 : 1,
			userId: getToken('useNum')
		}
		if (getToken('version') == 2) {
			params['companyNo'] = userId
		}
		addFriends(params).then(res => {
			if (res.data && res.data.code == 7) {
				store.commit('setUseState', {
					key: 'isApply',
					obj: true
				})
				uni.showToast({
					title:res.data && res.data.msg || '申请成功',
					icon:'none'
				})
				resolve(true)
			} else {
				store.commit('setUseState', {
					key: 'isApply',
					obj: false
				})
				uni.showToast({
					title:res.data && res.data.msg || '申请失败',
					icon:'none'
				})
				reject(false)
			}
		})
	})
	return adFriends(params)
}
// 极速联系
export async function callPeople(sendNum, phone, isShare) {
	if (phone && isShare) {
		if(test.mobile(phone)){
			uni.makePhoneCall({
				phoneNumber: phone
			})
		}
	} else if(!phone){
		//获取他人电话号码
		let params = {}
		getToken('version') == 1 ? params['craftsmanNo'] = sendNum : params['companyNo'] = sendNum
		getPeoPhone(params).then(res => {
			if (res.data && res.data.code == 1) {
				if (getToken('version') == 1) {
					uni.makePhoneCall({
						phoneNumber: (res.data && res.data.data && res.data.data.userTelephone)
					})
				} else if (getToken('version') == 2) {
					uni.makePhoneCall({
						phoneNumber: (res.data && res.data.data && res.data.data.companyTelephone)
					})
				}
			}
		})
	}
}
//新建联系人
export function setOnePeo(data) {
	if (!getToken('isLogin')) {
		store.dispatch('showAuthModal');
		return
	}
	data = String(data)
	let sendMsg = {
		action: 6,
		chatMsg: {
			selfNo: getToken('useNum'),
			entity: "usrChatObjectItem",
			friendNo: data
			// jobType:'',
			// createComNo:'',
			// objectComNo:'',
			// createType:1, 
			// objectType:1
		},
		extand: null
	}
	if (getToken('version') == 2) { //自己是企业
		//判断他人是不是企业
		if (Number(data.substr(0, 1)) % 2 == 0) { //对方是企业
			sendMsg.chatMsg.objectComNo = data
			sendMsg.chatMsg.createComNo = getToken('useNum')
			sendMsg.chatMsg.objectType = 1
			sendMsg.chatMsg.createType = 1
		} else if (Number(data.substr(0, 1)) % 2 == 1) { //对方是个人
			sendMsg.chatMsg.createComNo = getToken('useNum')
			sendMsg.chatMsg.createType = 1
			sendMsg.chatMsg.objectType = 0
		}
	} else if (getToken('version') == 1) { //自己是个人
		if ((data.substr(0, 1)) % 2 == 0) { //对方是企业
			sendMsg.chatMsg.objectComNo = data
			sendMsg.chatMsg.objectType = 1
			sendMsg.chatMsg.createType = 0
		} else if (Number(data.substr(0, 1)) % 2 == 1) { //对方是个人
			sendMsg.chatMsg.createComNo = getToken('useNum')
			sendMsg.chatMsg.createType = 0
			sendMsg.chatMsg.objectType = 0
		}
	}
	return sendMsg
}
// 获取随机字符串
export function getRandomWord(randomFlag, min, max) {
	let str = ''
	let range = min
	const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
		'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
		'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
	]
	// 随机产生
	if (randomFlag) {
		range = Math.round(Math.random() * (max - min)) + min
	}
	for (let i = 0; i < range; i++) { // eslint-disable-line
		const pos = Math.round(Math.random() * (arr.length - 1))
		str += arr[pos]
	}
	return str
}
export function pySegSort(arr, key) {
	if (!String.prototype.localeCompare) return null
	let letters = 'ABCDEFGHJKLMNOPQRSTWXYZ'.split('')
	let zh = '阿八嚓哒妸发旮哈讥咔垃痳拏噢妑七呥扨它穵夕丫帀'.split('')
	let segs = []
	letters.forEach((item, i) => {
		let cur = {
			letter: item,
			data: []
		}
		arr.forEach((item) => {
			// 返回值大于0：说明当前字符串string大于对比字符串targetString
			// 返回值小于0：说明当前字符串string小于对比字符串targetString
			// 返回值等于0：说明当前字符串string等于对比字符串targetString
			if (item[key].localeCompare(zh[i]) >= 0 && item[key].localeCompare(zh[i + 1]) < 0) {
				cur.data.push(item)
			}
		})
		if (cur.data.length) {
			cur.data.sort(function(a, b) {
				return a[key].localeCompare(b[key], 'zh')
			})
			segs.push(cur)
		}
	})
	return segs
}
